const { createEditor, createToolbar, SlateEditor, SlateTransforms } = window.wangEditor;
let currentHistory;
let videoUrlList = []
let selection;
var firstTitle = false;
let editorHeight;
window.onload = () => {
    //标题input自动增高
    let elem = document.getElementById("toolbar-container").getElementsByClassName("w-e-bar-item")[17].getElementsByTagName("button")[0]
    elem.addEventListener('click', function (e) {
    }, false)
    //苹果手机底部框页面遮挡
    if (!!window.navigator.userAgent.match(/iphone|ipad/gi)) {
        let editorWrapper = document.getElementById("editor—wrapper");
        let div = document.createElement("div")
        div.style = "height:50px"
        editorWrapper.appendChild(div)
    }
    document.getElementById("title").addEventListener("input", () => {
        editor.scrollToElem("editor-container")
        let el = document.getElementById("title")
        el.style.height = "auto";
        el.scrollTop = 0; // 防抖动
        el.style.height = (el.scrollHeight <= 68 ? el.scrollHeight : 68) + "px";
    })
}
//编辑器元素注册
const editorModule = {                      // JS 语法
    // menus: [menu1Conf, menu2Conf, menu3Conf], // 菜单// 插件
    renderElems: [renderBlockquote2ElemConf, renderBlockquote3ElemConf, renderTitle1Conf, renderTitle2Conf, renderTitle3Conf, renderThumbnailConf, renderEmojiConf, renderCustomImageConf], // renderElem
    elemsToHtml: [elemToblockquote2HtmlConf, elemToblockquote3HtmlConf, title1ToHtmlConf, title2ToHtmlConf, title3ToHtmlConf, thumbnailToHtmlConf, emojiToHtmlConf, customImageHtmlConf],
    parseElemsHtml: [parseblockquote2HtmlConf, parseblockquote3HtmlConf, parsetitle1HtmlConf, parsetitle2HtmlConf, parsetitle3HtmlConf, parseThumbnailHtmlConf, parseEmojiHtmlConf, parseCustomImageHtmlConf],
    editorPlugin: withAttachment
    // 其他功能，下文讲解...
}
Boot.registerModule(editorModule)

const editorConfig = {
    placeholder: '请输入正文',
    autoFocus: true,
    scroll: false,
    MENU_CONF: {},
    pasteFilterStyle: false,
 
    onChange(editor) {

        console.log(editor)
        const html = editor.getHtml()
        if (editor.getText() != '') {
            editorHtmlShow = true

        } else {
            editorHtmlShow = false
        }
        if (editor.isEmpty()) {
            window.android ?
                window.android.attributeChange(["font_align_default_1", "font_size_normal_2"]) :
                window.webkit.messageHandlers.attributeChange.postMessage(["font_align_default_1", "font_size_normal_2"])

        }
        //编辑器
        if (!notSave) {
            setTimeout(() => {
                let scrollTop;
                //距顶小于多少就
                if (editor.getSelectionPosition().top) {
                    scrollTop = parseInt(editor.getSelectionPosition().top.slice(0, -2)) + document.getElementById("title").clientHeight
                } else if (editor.getSelectionPosition().bottom) {
                    scrollTop = editor.getEditableContainer().getBoundingClientRect().height - parseInt(editor.getSelectionPosition().bottom.slice(0, -2)) + document.getElementById("title").clientHeight
                }
                if (!!window.navigator.userAgent.match(/iphone|ipad/gi)) {
                    window.scrollTo(0, scrollTop - 64)
                } else {
                    window.scrollTo(0, scrollTop - 44)
                }
            }, 50)
        }
        editorHeight = editor.getEditableContainer().getBoundingClientRect().height
        if (!selection) {
            selection = JSON.stringify(editor.selection);
        }
        let editorHistory = {
            undo: editor.history.undos.length > 0 ? 1 : 0,
            redo: editor.history.redos.length > 0 ? 1 : 0
        }
        if (currentHistory && (editorHistory.undo == 1 || editorHistory.redo == 1)) {
            if (JSON.stringify(currentHistory.undos) != JSON.stringify(editor.history.undos)) {
                // if (notSave) return
                window.android ?
                    window.android.saveDraft(JSON.stringify(getEditorHtml(0))) :
                    window.webkit.messageHandlers.saveDraft.postMessage(JSON.stringify(getEditorHtml(0)))
            }
        }
        currentHistory = JSON.parse(JSON.stringify(editor.history))
        window.android ?
            window.android.editorHistory(JSON.stringify(editorHistory)) :
            window.webkit.messageHandlers.editorHistory.postMessage(JSON.stringify(editorHistory))
        if (SlateEditor.marks(editor) || (editor.isEmpty() || JSON.stringify(editor.selection) != selection)) {
            selection = JSON.stringify(editor.selection);
            let marks = SlateEditor.marks(editor)
            let arr = []
            console.log(marks)
            if(marks!=null){}
            
            if (marks.fontSize) {
                if (marks.fontSize == "14px") {
                    arr.push("font_size_min_1")
                } else if (marks.fontSize == "17px") {
                    arr.push("font_size_normal_2")
                } else if (marks.fontSize == "20px") {
                    arr.push("font_size_big_3")
                } else if (marks.fontSize == "22px") {
                    arr.push("font_size_max_4")
                }
            } else {
                arr.push("font_size_normal_2")
                // editor.addMark("fontSize", "17px")
            }
            if (marks.bold) arr.push("font_bold_1")
            if (marks.italic) arr.push("font_italic_2")
            if (marks.underline) arr.push("font_underline_3")
            if (marks.through) arr.push("font_through_4")
            let color = {
                "#222222": "#222222_1",
                "#D9D9D9": "#D9D9D9_2",
                "#EF4142": "#EF4142_3",
                "#FE7429": "#FE7429_4",
                "#00AA54": "#00AA54_5",
                "#0289E3": "#0289E3_6",
                "#742BFE": "#742BFE_7"
            }
            let bgColor = {
                "reset": "reset_1",
                "#E4E4E4": "#E4E4E4_2",
                "#FCD2D4": "#FCD2D4_3",
                "#FBF1B3": "#FBF1B3_4",
                "#C3EDD9": "#C3EDD9_5",
                "#B6D2FA": "#B6D2FA_6",
                "#E0C8FF": "#E0C8FF_7"
            }
            let align = {
                "justify": "default_1",
                "left": "left_2",
                "center": "center_3",
                "right": "right_4"
            }
            if (marks.color && marks.color.includes("rgb")) {
                arr.push(`font_color_${color[colorRGBtoHex(marks.color).toUpperCase()]}`)
            } else if (marks.color) {
                arr.push(`font_color_${color[marks.color]}`)

            } else {
                editor.addMark("color", "#222222");
                arr.push(`font_color_#222222_1`)
            }
            if (marks.bgColor && marks.bgColor.includes("rgb")) {
                arr.push(`font_bg_${bgColor[colorRGBtoHex(marks.bgColor).toUpperCase()]}`)
            } else if (marks.bgColor) arr.push(`font_bg_${bgColor[marks.bgColor]}`)
            else { arr.push(`font_bg_reset_1`) }
            const nodeEntries = SlateEditor.nodes(editor, {
                match: (node) => {          // JS syntax
                    if (SlateElement.isElement(node)) {
                        if (node.type === 'paragraph' || node.type === 'numbered-list' || node.type === 'bulleted-list' ||
                            node.type.includes("blockquote") || node.type.includes("title")) {
                            return true // 匹配 paragraph
                        }
                    }
                    return false
                },
                universal: true,
            })
            for (let nodeEntry of nodeEntries) {
                const [node, path] = nodeEntries
                if (nodeEntry[0].type == "paragraph") {
                    if (nodeEntry[0].textAlign) {
                        arr.push(`font_align_${align[nodeEntry[0].textAlign]}`)
                    } else {
                        arr.push(`font_align_default_1`)
                    }
                } else if (nodeEntry[0].type == "numbered-list" || nodeEntry[0].type == "bulleted-list") {
                    nodeEntry[0].type == "numbered-list" ? arr.push(`style_list_2`) : arr.push(`style_list_1`)
                    if (nodeEntry[0].children[0].textAlign) {
                        arr.push(`font_align_${align[nodeEntry[0].children[0].textAlign]}`)
                    } else {
                        arr.push(`font_align_default_1`)
                    }
                } else if (nodeEntry[0].type == "blockquote" || nodeEntry[0].type == "blockquote2" || nodeEntry[0].type == "blockquote3") {

                    arr.push(nodeEntry[0].type == "blockquote" ? "style_cite_2" : nodeEntry[0].type == "blockquote2" ? "style_cite_1" : "style_cite_3")


                } else if (nodeEntry[0].type == "title1" || nodeEntry[0].type == "title2" || nodeEntry[0].type == "title3") {
                    arr.push("style_title_" + nodeEntry[0].type.substr(-1))
                }
            }
            window.android ?
                window.android.attributeChange(arr) :
                window.webkit.messageHandlers.attributeChange.postMessage(arr)
        }
    },
    //自定义粘贴
    customPaste(editor) {
        //对移动端文字复制粘贴样式消失情况进行处理
        const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
        const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
        let parser = new DOMParser();
        let doc = parser.parseFromString(html, "text/html");
        if (html.includes("data-slate-fragment=") && html.includes("data-slate-fragment=") != -1) {
            let fragment = html.slice(html.indexOf("data-slate-fragment=") + 21)
            fragment = fragment.slice(0, fragment.indexOf("\""))
            const decoded = decodeURIComponent(window.atob(fragment))
            const parsed = JSON.parse(decoded)
            editor.insertFragment(parsed)
            return false
        } else {
            // 继续执行默认的粘贴行为
            return true
        }
        // for (let i in doc.getElementsByTagName("span")) {
        //     if (doc.getElementsByTagName("span")[i].attributes && !!doc.getElementsByTagName("span")[i].getAttribute("data-slate-fragment")) {
        //         const decoded = decodeURIComponent(window.atob(doc.getElementsByTagName("span")[i].getAttribute("data-slate-fragment")))
        //         const parsed = JSON.parse(decoded)
        //         editor.insertFragment(parsed)
        //         return false;
        //     } else {
        //         return true;
        //     }
        // }
    }
}
editorConfig.MENU_CONF["fontSize"] = {
    fontSizeList: [
        "12px",
        "13px",
        "14px",
        "15px",
        "16px",
        "17px",
        "18px",
        "19px",
        "20px",
        "22px",
        "24px",
    ],
};
const editor = createEditor({
    selector: '#editor-container',
    html: '<p><br></p>',
    config: editorConfig,
    mode: 'default', // or 'simple'
})

const toolbarConfig = {}
const toolbar = createToolbar({
    editor,
    selector: '#toolbar-container',
    config: toolbarConfig,
    mode: 'default', // or 'simple'
})
